package com.demo.executor;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.demo.engine.HttpEngine;
import com.demo.engine.entity.BackData;
import com.demo.engine.entity.Scouter;
import com.demo.parsers.BaseParser;
import com.demo.thread.ExecutorManager;
import com.demo.utils.InputStreamUtils;

public class HttpConnector implements IExecutor {

	private static final String TAG = "HttpConnector";

	private Scouter scouter;
	private BackData backData;
	private ExecutorCallBackListener executorCallBackListener;

	public void setExecutorCallBackListener(ExecutorCallBackListener executorCallBackListener) {
		this.executorCallBackListener = executorCallBackListener;
	}

	@Override
	public void request(Scouter scouter) {
		this.scouter = scouter;
		this.backData = this.scouter.getBackData();
		ExecutorManager.getInstance().push(this);
	}

	@Override
	public void run() {
		HttpEngine httpEngine = new HttpEngine();
		byte[] byteArr = httpEngine.request(this.scouter);
		if (byteArr == null) {
			Log.w(TAG, "HttpEngine request is error.");
			backData.setSuccess(false);
			backData.setMsg("HttpEngine request is error.");
		} else {
			String jsonData = InputStreamUtils.byteToString(byteArr);
			backData.setSuccess(true);
			BaseParser parser = scouter.getParser();
			if (parser != null) {
				parser.Parse(jsonData, backData);
			} else {
				backData.setSuccess(false);
				backData.setMsg("Parser is null");
			}
		}
		sendMessage(backData);
		ExecutorManager.getInstance().didComplete(this);
	}

	private void sendMessage(BackData backData) {
		Message msg = handler.obtainMessage(0, backData);
		handler.sendMessage(msg);
	}

	private final Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			BackData backData = (BackData) msg.obj;
			if (executorCallBackListener != null && backData != null) {
				executorCallBackListener.executorCallback(backData);
			}
		};
	};
}
